﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MathTest
{
    public partial class AnswerQuestionsForm : Form
    {
        #region 属性
        /// <summary>
        /// 考试记录集
        /// </summary>
        private List<Entity.TestResults> testResultsList = new List<Entity.TestResults>();
        /// <summary>
        /// 单条试题结果实体
        /// </summary>
        private Entity.TestResults entiyTestResults = new Entity.TestResults();
        /// <summary>
        /// 试题库
        /// </summary>
        private List<Entity.MathOperation> MathOperationList = new List<Entity.MathOperation>();
        /// <summary>
        /// 序列化实例
        /// </summary>
        private IFormatter formatter = new BinaryFormatter();
        /// <summary>
        /// 倒计时时间
        /// </summary>
        private int countdown = 60;
        /// <summary>
        /// 题库试题数量
        /// </summary>
        private int currentTitleNumber = 0;

        private int Countdown
        {
            get { return countdown; }
            set
            {
                countdown = value;
                toolStripStatusLabel2.Text = countdown.ToString();
            }
        }
        #endregion

        #region 构造函数
        public AnswerQuestionsForm()
        {
            InitializeComponent();
        }
        #endregion

        #region 事件
        private void AnswerQuestionsForm_Load(object sender, EventArgs e)
        {
            //读取试题库
            if (File.Exists(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "mathbank.txt"))
            {
                //读取实体类集
                Stream readstream = new FileStream(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "mathbank.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
                MathOperationList = (List<Entity.MathOperation>)formatter.Deserialize(readstream);
                readstream.Close();
            }
            entiyTestResults.TestSumCount = MathOperationList.Count;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认退出吗？如果题目没有回答完成，本次结果将不保存。", this.Text, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
            {
                this.Close();
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {

            try
            {
                if (txtStudentsName.Text == "")
                {
                    MessageBox.Show("请填写测试者的名字。", this.Text);
                    InitInterface();
                    return;
                }
                //确认试题库不为空
                if (MathOperationList.Count > 0)
                {
                    lblFirstOperand.Text = MathOperationList[0].firstOperand;
                    lblOperator.Text = MathOperationList[0].signOperation;
                    lblSecondOperand.Text = MathOperationList[0].secondOperand;
                    btnStart.Enabled = false;//测试开始之后该按钮停用
                    Countdown = 60;//初始化倒计时器
                    timer1.Enabled = true; //启动计时器。
                    btnConfirm.Enabled = true;


                    label8.Text = MathOperationList.Count().ToString();
                    label10.Text = (currentTitleNumber + 1).ToString();

                    entiyTestResults.ID = Guid.NewGuid().ToString();//采用guid当作主键
                    entiyTestResults.studentsName = txtStudentsName.Text;
                    entiyTestResults.testDateTime = DateTime.Now;   //使用当前时间
                    entiyTestResults.TestResultsItemList = new List<Entity.TestResultsItem>();
                    entiyTestResults.testCorrectCount = 0;
                    entiyTestResults.testCorrectRatio = "";
                }
                else
                {
                    MessageBox.Show("请到试题库管理中添加试题。", this.Text);
                    return;
                }
                //读取试题结果记录
                if (File.Exists(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "log.txt"))
                {
                    //读取实体类集
                    Stream readstream = new FileStream(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "log.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
                    testResultsList = (List<Entity.TestResults>)formatter.Deserialize(readstream);
                    readstream.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, this.Text);
            }
        }
        private void btnConfirm_Click(object sender, EventArgs e)
        {
            if (currentTitleNumber < MathOperationList.Count())
            {
                //初始化本次考试记录
                decimal result = 0;
                label10.Text = (currentTitleNumber + 1).ToString();
                //将考题显示到界面
                if (decimal.TryParse(txtResult.Text, out result)) //验证格式
                {
                    //验证答题结果
                    if (result == decimal.Parse(MathOperationList[currentTitleNumber].results))
                    {
                        entiyTestResults.TestResultsItemList.Add(new Entity.TestResultsItem { testQuestions = lblFirstOperand.Text + lblOperator.Text + lblSecondOperand.Text + "=" + txtResult.Text, testResult = "正确" });
                        entiyTestResults.testCorrectCount = entiyTestResults.testCorrectCount + 1;
                    }
                    else
                    {
                        entiyTestResults.TestResultsItemList.Add(new Entity.TestResultsItem { testQuestions = lblFirstOperand.Text + lblOperator.Text + lblSecondOperand.Text + "=" + txtResult.Text, testResult = "错误" });
                    }

                }
                else
                {
                    MessageBox.Show("请输入数字，不要输入其他字符。", this.Text);
                    return;
                }
                currentTitleNumber = currentTitleNumber + 1;
                txtResult.Text = "";
                if (currentTitleNumber < MathOperationList.Count())
                {
                    lblFirstOperand.Text = MathOperationList[currentTitleNumber].firstOperand;
                    lblOperator.Text = MathOperationList[currentTitleNumber].signOperation;
                    lblSecondOperand.Text = MathOperationList[currentTitleNumber].secondOperand;
                }
                if (currentTitleNumber == MathOperationList.Count())
                {
                    SaveTestResult();
                    InitInterface();
                    string resultstr = "";
                    if (entiyTestResults.TestResultsItemList.Count > 0)
                    {
                        foreach (var item in entiyTestResults.TestResultsItemList)
                        {
                            resultstr = resultstr + item.testQuestions + "  " + item.testResult + "\r\n";
                        }
                    }
                    MessageBox.Show("答题完毕。\r\n" + resultstr + "\r\n总题数:" + entiyTestResults.TestSumCount.ToString() + " 正确数量：" + entiyTestResults.testCorrectCount.ToString() + " 正确率:" + entiyTestResults.testCorrectRatio, this.Text);

                }
            }
            else
            {

            }
        }

        private void txtResult_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnConfirm_Click(sender, e);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            Countdown = countdown - 1;
            if (countdown == 0)
            {
                SaveTestResult();
                MessageBox.Show("本次考试结束。", this.Text);
                InitInterface();
            }
        }


        #endregion

        #region 方法
        /// <summary>
        /// 保存考试结果
        /// </summary>
        private void SaveTestResult()
        {
            if (entiyTestResults.TestSumCount > 0)
            {
                entiyTestResults.testCorrectRatio = entiyTestResults.testCorrectCount / entiyTestResults.TestSumCount * 100 + "%";
            }
            testResultsList.Add(entiyTestResults);
            Stream writestream = new FileStream(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "log.txt", FileMode.Create, FileAccess.Write, FileShare.None);
            formatter.Serialize(writestream, testResultsList);
            writestream.Close();
        }

        /// <summary>
        /// 初始化控件状态
        /// </summary>
        private void InitInterface()
        {
            btnStart.Enabled = true;
            btnConfirm.Enabled = false;
            timer1.Enabled = false; //停止计时器
            Countdown = 60;
            currentTitleNumber = 0;
            txtStudentsName.Text = "";
            lblFirstOperand.Text = "";
            lblOperator.Text = "";
            lblSecondOperand.Text = "";
            txtResult.Text = "";
        }


        #endregion
    }
}
